<?php
class view_table extends view {
	
	public $sort = array();
	public $filter = array();
	
	function __construct($modelname) {
		parent::__construct($modelname, "table");
	}
	
	function getDefaultOrder() {
		foreach($this->structure as $field) {
			if ($field->order_default == "true") {
				return $field->name;
			}
		}
		error::warning("No default order field set for model {$this->modelname} in table view");
		return "id";
	}
	
	function getTableData() {
		// get order		
		$this->sort["by"] = request::get("sortby") ? request::get("sortby") : $this->getDefaultOrder();
		$this->sort["dir"] = request::get("sortdir") ? request::get("sortdir") : "asc";
		
		// get filter
		$this->filter["field"] = request::get("filterfield");
		$this->filter["on"] = request::get("filteron");
		
		// build query		
		$query = new query();
		$query->setTable($this->modelname);
		
		// always load id
		if (!in_array("id", $this->getFieldNames())) {
			$query->addSelect("id");
		}
		$query->addSelect($this->getFieldNames());
		$query->setOrder($this->sort);
		
		// filter?
		if ($this->filter["field"] && $this->filter["on"]) {
			$query->setWhere($this->filter["field"] . " = " . $this->filter["on"]);
		}
		
		return $this->loadModel()->query($query);
	}
	
	function switchOrderDir($dir) {
		return strtolower($dir) == "asc" ? "desc" : "asc";
	}

}
?>